package com.itheima.tliasmanagent.filter;

import com.itheima.tliasmanagent.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;

import java.io.IOException;

//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1. 获取请求路径
        String url = request.getRequestURL().toString();
        //2. 判断是否是登录的请求 如果是 直接放行
        if(url.contains("login")){
            filterChain.doFilter(request,response);
            return;
        }
        //3.从请求头中获取token
        String jwt = request.getHeader("token");
        //4. 判断token是否存在  不存在返回  401
        if(jwt == null || jwt.length() ==0){
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        //5. 解析token 如果解析失败 返回401
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        //6. 放行
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
